package cn.iocoder.yudao.module.member.controller.admin.user;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserPriceDetailRespDTO;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserPriceRespDTO;
import cn.iocoder.yudao.module.member.controller.admin.user.vo.*;
import cn.iocoder.yudao.module.member.controller.app.user.vo.AppMemberUserInfoRespVO;
import cn.iocoder.yudao.module.member.controller.app.user.vo.AppMemberUserPriceUpdateReqVO;
import cn.iocoder.yudao.module.member.controller.app.user.vo.AppMemberUserResetPasswordReqVO;
import cn.iocoder.yudao.module.member.convert.user.MemberUserConvert;
import cn.iocoder.yudao.module.member.convert.user.MemberUserPriceConvert;
import cn.iocoder.yudao.module.member.convert.user.MemberUserPriceDetailConvert;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserPriceDetailDo;
import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserPriceDo;
import cn.iocoder.yudao.module.member.enums.point.MemberPointBizTypeEnum;
import cn.iocoder.yudao.module.member.service.group.MemberGroupService;
import cn.iocoder.yudao.module.member.service.point.MemberPointRecordService;
import cn.iocoder.yudao.module.member.service.tag.MemberTagService;
import cn.iocoder.yudao.module.member.service.user.MemberUserPriceDetailService;
import cn.iocoder.yudao.module.member.service.user.MemberUserPriceService;
import cn.iocoder.yudao.module.member.service.user.MemberUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;

@Tag(name = "管理后台 - 会员用户")
@RestController
@RequestMapping("/member/user")
@Validated
public class MemberUserController {

    @Resource
    private MemberUserService memberUserService;
    @Resource
    private MemberTagService memberTagService;
//    @Resource
//    private MemberLevelService memberLevelService;
    @Resource
    private MemberGroupService memberGroupService;
    @Resource
    private MemberPointRecordService memberPointRecordService;
    @Resource
    private MemberUserPriceService memberUserPriceService;
    @Resource
    private MemberUserPriceDetailService memberuserpricedetailservice;

//    @PutMapping("/createUserFront")
//    @Operation(summary = "前端创建会员用户")
//    @PreAuthorize("@ss.hasPermission('member:user:createfront')")
//    public CommonResult<Boolean> createUserFront(@Valid @RequestBody MemberUserVo memberUserVo) {
//        memberUserService.createUserFront(memberUserVo);
//        return success(true);
//    }
    @PutMapping("/update")
    @Operation(summary = "更新会员用户")
    @PreAuthorize("@ss.hasPermission('member:user:update')")
    public CommonResult<Boolean> updateUser(@Valid @RequestBody MemberUserUpdateReqVO updateReqVO) {
        memberUserService.updateUser(updateReqVO);
        return success(true);
    }

    @PostMapping("/sendEmail")
    @Operation(summary = "发送邮件")
    @PreAuthorize("@ss.hasPermission('member:user:send_email')")
    public CommonResult<Boolean> sendEmail(@Valid @RequestBody MemBerSendEmail memBerSendEmail) {
        memberUserService.sendEmail(memBerSendEmail);
        return success(true);
    }

    @PostMapping("/update-point")
    @Operation(summary = "更新会员用户积分")
    @PreAuthorize("@ss.hasPermission('member:user:update-point')")
    public CommonResult<Boolean> updateUserPoint(@Valid @RequestBody MemberUserUpdatePointReqVO updateReqVO) {
        memberUserService.updateRecord(updateReqVO.getId(), updateReqVO.getPoint(),
                 String.valueOf(getLoginUserId()),updateReqVO.getAddFlag());
        return success(true);
    }

    @PostMapping("/update-device")
    @Operation(summary = "更新会员用户设备数量")
    @PreAuthorize("@ss.hasPermission('member:user:update-device')")
    public CommonResult<Boolean> updateUserDevice(@Valid @RequestBody MemberUserUpdateDeviceReqVO updateReqVO) {
        memberUserService.updateUserDevice(updateReqVO.getId(), updateReqVO.getPoint(),updateReqVO.getAddFlag());
        return success(true);
    }

    @PostMapping("/update-batchInfo")
    @Operation(summary = "更新批量签名信息")
    @PreAuthorize("@ss.hasPermission('member:user:update-batchInfo')")
    public CommonResult<Boolean> updateBatchInfo(@Valid @RequestBody MemberUserUpdateBatchReqVO updateReqVO) {
        memberUserService.updateBatchInfo(updateReqVO);
        return success(true);
    }


    @GetMapping("/get")
    @Operation(summary = "获得会员用户")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('member:user:query')")
    public CommonResult<MemberUserRespVO> getUser(@RequestParam("id") Long id) {
        MemberUserDO user = memberUserService.getUser(id);
//        用户配置详情
        List<MemberUserPriceDo> userByUserId = memberUserPriceService.getUserByUserId(id);
        List<MemberUserPriceRespDTO> memberUserPriceRespDTOS = MemberUserPriceConvert.INSTANCE.convertList2(userByUserId);
        MemberUserRespVO memberUserRespVO = MemberUserConvert.INSTANCE.convert03(user);
        List<MemberUserPriceDetailDo> userByUserId1 = memberuserpricedetailservice.getUserByUserId(id);
        List<MemberUserPriceDetailRespDTO> memberUserPriceDetailRespDTOS = MemberUserPriceDetailConvert.INSTANCE.convertList2(userByUserId1);
        Map<String,List<MemberUserPriceDetailRespDTO>> map = new HashMap<>();
        memberUserPriceDetailRespDTOS.forEach(t->{
            if (map.containsKey(t.getPriceCode())){
                List<MemberUserPriceDetailRespDTO> memberUserPriceDetailRespDTOS1 = map.get(t.getPriceCode());
                memberUserPriceDetailRespDTOS1.add(t);
                map.remove(t.getPriceCode());
                map.put(t.getPriceCode(),memberUserPriceDetailRespDTOS1);
            }else {
                List<MemberUserPriceDetailRespDTO> memberUserPriceDetailRespDTOS1 = new ArrayList<>();
                memberUserPriceDetailRespDTOS1.add(t);
                map.put(t.getPriceCode(),memberUserPriceDetailRespDTOS1);
            }
        });
        memberUserPriceRespDTOS.forEach(t->{
            if (map.containsKey(t.getPriceCode())){
                t.setDetails(map.get(t.getPriceCode()));
            }
        });
        memberUserRespVO.setVoList(memberUserPriceRespDTOS);
        return success(memberUserRespVO);
    }

    @PostMapping("/page")
    @Operation(summary = "获得会员用户分页")
    @PreAuthorize("@ss.hasPermission('member:user:query')")
    public CommonResult<PageResult<MemberUserRespVO>> getUserPage(@Valid  @RequestBody MemberUserPageReqVO pageVO) {
        PageResult<MemberUserDO> pageResult = memberUserService.getUserPage(pageVO);
        if (CollUtil.isEmpty(pageResult.getList())) {
            return success(PageResult.empty());
        }
        return success(MemberUserConvert.INSTANCE.convertPage(pageResult));
    }


    @PostMapping("/enable")
    @Operation(summary = "启用会员")
    @PreAuthorize("@ss.hasPermission('member:user:enable')")
    public CommonResult<Boolean> enable(@RequestBody UpdateStatusVo  vo) {
        memberUserService.enable(vo.getIds(),vo.getType());
        return success(true);
    }
    @PostMapping("/disable")
    @Operation(summary = "启用会员")
    @PreAuthorize("@ss.hasPermission('member:user:disable')")
    public CommonResult<Boolean> disable(@RequestBody UpdateStatusVo  vo) {
        memberUserService.disable(vo.getIds(),vo.getType());
        return success(true);
    }
    @PostMapping("/updateByBackend")
    @Operation(summary = "后台更新用户信息")
    @PreAuthorize("@ss.hasPermission('member:user:update:backend')")
    public CommonResult<Boolean> updateByBackend(@Valid @RequestBody MemberUserUpdateVo updateReqVO) {
        memberUserService.updateByBackend(updateReqVO);
        return success(true);
    }

    @GetMapping("/delete")
    @Operation(summary = "删除")
    @PreAuthorize("@ss.hasPermission('member:user:delete')")
    public CommonResult<Boolean> delete( String id) {
        memberUserService.delete(id);
        return success(true);
    }
    @GetMapping("/reset-password")
    @Operation(summary = "重置密码", description = "用户忘记密码时使用")
    @PreAuthorize("@ss.hasPermission('member:user:reset-password')")
    public CommonResult<Boolean> resetUserPassword(@Param("id") Long id) {
        memberUserService.resetPasswordByAdmin(id);
        return success(true);
    }

}
